<?php

namespace Data;

use Business\Breed;

class User extends Base {

	/**
	 * 饮食习惯：狗粮
	 */
	const EATING_HABITS_DOG_FOOD = 1;

	/**
	 * 饮食习惯：自制
	 */
	const EATING_HABITS_DOG_DIY = 2;

	/**
	 * 饮食习惯：混合
	 */
	const EATING_HABITS_DOG_MIXED = 3;

	/**
	 * 是否生孕：是
	 */
	const HAS_CHILDREN_YES = 1;

	/**
	 * 是否生孕：否
	 */
	const HAS_CHILDREN_NO = 2;

	/**
	 * 是否生孕：保密
	 */
	const HAS_CHILDREN_KEEP = 3;

	/**
	 * 用户登录标记的前缀.
	 */
	const USER_LOGIN_MASK = 'user_login_mask';

	const USER_OAUTH_ID = 'user_oauth_mask';

	public function getUserInfoByEmail($email, $isOk = false) {
		$email = trim($email);
		$email = strtolower($email);
		$condition = array(
			'Email' => $email,
		);
		if ($isOk) {
			$condition['Status'] = \Data\Base::IS_YES;
		}
		$user = $this->where($condition)->findOne();
		return $user;
	}

	public function getUserByIds($userIds) {
		if (!$userIds) {
			return array();
		}
		$condition = array(
			'UserId in' => $userIds,
		);
		$users = $this->where($condition)->findAll('UserId');
		return $users;
	}

	public function getUserIdByUserId($userId) {
		$condition = array(
			'UserId' => $userId,
			'Status' => self::IS_YES,
		);
		$i = $this->select('UserId')->where($condition)->findOne();
		if ($i) {
			return (int) $i['UserId'];
		}
		return 0;
	}

	public function getUserInfoByUsername($username, $isOk = false) {
		$condition = array(
			'Username' => $username,
		);
		if ($isOk) {
			$condition['Status'] = \Data\Base::IS_YES;
		}
		$user = $this->where($condition)->findOne();
		return $user;
	}

	public function addUser($email, $password, $ip, $username = '', $photo = '') {
		$email = trim($email);
		$email = strtolower($email);
		$data = array(
			'Email' => $email,
			'Username' => $username,
			'Password' => $password,
			'CreateTime' => time(),
			'UpdateTime' => time(),
			'RegisterIp' => $ip,
			'Status' => self::IS_YES,
		);
		if ($photo) {
			$data['Photo'] = $photo;
		}
		return $this->insert($data);
	}

	public function addLoginLog($userId, $loginTime, $ip) {
		$data = array(
			'UserId' => $userId,
			'LoginTime' => $loginTime,
			'Ip' => $ip
		);
		$this->from('LoginLog')->insert($data);
	}

	/**
	 * 设置用户的一个登录标记.
	 *
	 * @param string  $mask 用户cookie中的唯一值.
	 * @param integer $uid  用户id.
	 *
	 * @return void
	 */
	public function setUserLoginMask($mask, $uid) {
		$redis = $this->getRedis();
		$key = self::USER_LOGIN_MASK . $mask;
		$redis->set($key, $uid);
		$redis->expire($key, 86400);
	}

	public function setUserAuthId($mask, $authId) {
		$redis = $this->getRedis();
		$key = self::USER_OAUTH_ID . $mask;
		$redis->set($key, $authId);
		$redis->expire($key, 86400);
	}

	public function delUserLoginMask($mask) {
		$redis = $this->getRedis();
		$key = self::USER_LOGIN_MASK . $mask;
		$redis->del($key);
		$redis->del(self::USER_OAUTH_ID . $mask);
	}

	public function getOAuthInfoByMask($mask) {
		$redis = $this->getRedis();
		$key = self::USER_OAUTH_ID . $mask;
		$id = $redis->get($key);
		$info = array();
		if ($id) {
			$info = OAuth::instance()->getById($id);
		}
		return $info;
	}

	/**
	 * 获取当前用户的信息.
	 *
	 * @param string $mask 用户cookie中的唯一值.
	 *
	 * @return array
	 */
	public function getCurrentUserInfo($mask) {
		$uid = $this->getCurrentUid($mask);
		$userInfo = array();
		if (empty($uid)) {
			return $userInfo;
		}
		// 用uid获取数据库中的用户信息
		$userInfo = $this->getUserInfoByUid($uid);
        if (!$userInfo) {
            return $userInfo;
        }
        if ($userInfo['BreedId']) {
            $userInfo['BreedName'] = Breed::instance()->getNameById($userInfo['BreedId']);
        } else {
            $userInfo['BreedName'] = '';
        }
		return $userInfo;
	}

	/**
	 * 通过用户id获取用户信息.
	 *
	 * @param integer $uid 用户id.
	 *
	 * @return array
	 */
	public function getUserInfoByUid($uid) {
		$condition = array(
			'UserId' => $uid
		);
		$userInfo = $this->where($condition)->findOne();
		return $userInfo;
	}

	public function updateById($userId, $data) {
		$condition = array(
			'UserId' => $userId,
		);
		$data['UpdateTime'] = time();
		$this->where($condition)->update($data);
	}

	public function updateUserPhoto($userId, $file) {
		$condition = array(
			'UserId' => $userId,
		);
		$data = array(
			'Photo' => $file,
		);
		$data['UpdateTime'] = time();
		$this->where($condition)->update($data);
	}

	public function updateUserInfo($userId, $user) {
		$condition = array(
			'UserId' => $userId,
		);
		$this->where($condition)->update($user);
	}

	public function getIndexUser($limit = 20) {
		$condition = array(
			'Status' => self::IS_YES,
		);
		$users = $this->where($condition)->order('UserId desc')->limit($limit)->findAll();
		return $users;
	}

	public function getTopUserByBreedId($breedId, $limit = 10) {
		$condition = array(
			'BreedId' => $breedId,
			'Status' => self::IS_YES,
		);
		$users = $this->where($condition)->order('UserId desc')->limit($limit)->findAll();
		return $users;
	}

	public function getMaxMoreBreedIds($limit = 4) {
		$condition = array(
			'BreedId >' => 0,
			'Status' => self::IS_YES,
			'Photo !=' => '',
		);
		$result = $this->select('count(*) as n, BreedId')
			->from('User')
			->where($condition)
			->group('BreedId')
			->order('n desc')
			->limit($limit)
			->findAll();
		$breedIds = array();
		foreach ($result as $val) {
			$breedIds[] = $val['BreedId'];
		}
		return $breedIds;
	}

	public function search($pager, $city = 0, $breedIds = 0, $sex = 0, $hasPhoto = false, $notUserIds = array()) {
		$condition = array();
		$condition['Status'] = self::IS_YES;
		if ($breedIds) {
			$condition['BreedId in'] = $breedIds;
		}
		if ($sex && in_array($sex, array(self::SEX_BOY, self::SEX_GIRL))) {
			$condition['Sex'] = $sex;
		}
		if ($hasPhoto) {
			$condition['Photo !='] = '';
		}
		if ($notUserIds) {
			$condition['UserId not in'] = $notUserIds;
		}
		if ($city) {
			if ($city < 1000000000) {
				$city = $city * 1000;
			}
			$condition['City >'] = 0;
			$this->select('*, (CASE WHEN City < 1000000000 THEN ABS(City * 1000 - ' . $city . ') ELSE ABS(City - ' . $city . ') END) as diff');
			$this->order('diff asc, UserId desc');
			$this->group('UserId');
			$this->having(array('diff <=' => 1000000000));
			if (!is_numeric($pager)) {
				$this->pager($pager, true);
			} else {
				$this->limit($pager);
			}
		} else {
			$this->select('*');
			$this->order('UserId desc');
			if (!is_numeric($pager)) {
				$this->pager($pager);
			} else {
				$this->limit($pager);
			}
		}

		$users = $this->where($condition)
			->findAll();
		return $users;
	}

	/**
	 * 获取当前用户的Uid.
	 *
	 * @param string $mask 用户cookie中的唯一值.
	 *
	 * @return integer
	 */
	private function getCurrentUid($mask) {
		$redis = $this->getRedis();
		$key = self::USER_LOGIN_MASK . $mask;
		$uid = $redis->get($key);
		return $uid;
	}

}